import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/components/input/my_search_input.dart';
import 'package:wallpaper/model/image_base.dart';

class SearchImage extends StatefulWidget {
  const SearchImage({super.key});

  @override
  State<SearchImage> createState() => _SearchImageState();
}

class _SearchImageState extends State<SearchImage> {
  final TextEditingController controller = TextEditingController();
  int page = 1;
  final List<ImageBase> imgs = [];
  bool isLoading = false;

  Future<void> getData() async {
    if (!mounted || isLoading) return; // 防止重复加载
    setState(() {
      isLoading = true;
    });

    try {
      Response res = await getDtImgs(keyword: controller.text, page: page);
      var data =
          json.decode(res.data); // 注意：若接口返回已是 JSON，可直接用 res.data 无需 decode

      if (data['code'] == 0) {
        final newImages = <ImageBase>[]; // 临时列表批量存储，减少 setState 次数
        for (var i = 0; i < data['data'].length; i++) {
          newImages.add(ImageBase(
            smallPath: data['data'][i]['pic']['path'],
            largePath: data['data'][i]['pic']['path'],
            tags: data['data'][i]['desc'],
            width: data['data'][i]['pic']['width'],
            height: data['data'][i]['pic']['height'],
          ));
        }

        setState(() {
          imgs.addAll(newImages); // 批量添加，仅触发 1 次重建
        });
      }
    } catch (e) {
      print(' 加载图片错误: $e'); // 增加错误上下文，便于调试
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  void _handleSearchSubmitted(String value) {
    FocusScope.of(context).unfocus(); // 简洁失焦，替代原 requestFocus (FocusNode ())
    imgs.clear();
    page = 1;
    getData();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;

    return RepaintBoundary(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: const Text(''),
          toolbarHeight: 0,
          elevation: 0,
          leading: null,
          backgroundColor: theme.primaryContainer,
          surfaceTintColor: theme.primaryContainer,
        ),
        body: Column(
          children: [
            const RepaintBoundary(
              child: _SearchInputWrapper(),
            ),
            Expanded(
              child: ImageList(
                imageList: imgs,
                isLoading: isLoading,
                isWaterfallFlow: true,
                onImageBottomLoading: () {
                  if (!isLoading) {
                    page++;
                    getData();
                  }
                },
                onImageListRefresh: () {
                  imgs.clear();
                  page = 1;
                  getData();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 6. 搜索框独立组件：仅负责搜索框渲染，状态通过父组件获取
class _SearchInputWrapper extends StatelessWidget {
  const _SearchInputWrapper();

  @override
  Widget build(BuildContext context) {
// 安全获取父组件状态，不破坏封装
    final parentState = context.findAncestorStateOfType<_SearchImageState>()!;

    return MySearchInput(
      controller: parentState.controller,
      onSubmitted: (v) => parentState._handleSearchSubmitted(v),
    );
  }
}
